package com.customization.api.e9sso.cmd;

import com.alibaba.fastjson.JSONObject;
import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DispatchSSFCmd4Kb202008 extends AbstractCommonCommand<Map<String,Object>> {

    private HttpServletRequest request=null;

    private String appid;
    public DispatchSSFCmd4Kb202008(User user, HttpServletRequest request) {
        this.user = user;
        this.params =  ParamUtil.request2Map(request);
        params=this.getHeadersInfo(request,params);
        this.request=request;
        appid=Util.null2String(params.get("appid"));

    }

    private Map<String, Object> getHeadersInfo(HttpServletRequest request,Map<String, Object> map) {

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String uuid= UUID.randomUUID().toString();
        Console.log(uuid+"输入参数params:"+params.toString());

        Map<String, Object> apidatas = new HashMap<String, Object>();
        apidatas.put("status",true);
        apidatas.put("msg","派单成功!");

        RecordSet rs=new RecordSet();
        RecordSet rst=new RecordSet();



        String requestId=Util.null2String(params.get("requestId"));
        String dispatchWorkcode=Util.null2String(params.get("dispatchWorkcode"));
        if(requestId.equals("")||dispatchWorkcode.equals("")){
            apidatas.put("status",false);
            apidatas.put("msg","必要参数不能为空或者不存在");
            Console.log(uuid+"返回值:"+apidatas.toString());
            return apidatas;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String cjsj = formatter.format(date);

        Console.log(uuid+"中的'"+user.getUID()+"'把'"+requestId+"'派给"+dispatchWorkcode);
        boolean b=rs.execute("insert into uf_DispatchSSF (cjsj,request_id,oper_workcode) values('"+cjsj+"','"+requestId+"','"+dispatchWorkcode+"')");
        if(!b) {
            apidatas.put("status",false);
            apidatas.put("msg", "派单失败!");
            Console.log(uuid+"返回值:"+apidatas.toString());
            return apidatas;
        }


        //判断流程是否在当前SSF派单环节
        String secSql=  "select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where  " +
                " workflow_flownode.nodeid=workflow_nodebase.id  " +
                "  and  workflow_requestbase.workflowid=workflow_flownode.workflowid  and workflow_requestbase.CURRENTNODEID=workflow_flownode.nodeid " +
                " and workflow_requestbase.requestid='"+requestId+"' and  workflow_nodebase.NODENAME like '%共享派单%' ";
        boolean isSSFNode=false;//是否在SSF 派单环节
        rs.execute(secSql);
        if(rs.next()){
            isSSFNode=true;
        }


        if(!isSSFNode) {//如果不在SSF发起节点 这检查上一次是否派单成功
            //2021/3/31 17:40 lth    增加派单成功之后的单据
            rs.execute("select * from uf_DispatchSSF where request_id='" + requestId + "' and lctjzt='0' and  cjsj!='" + cjsj + "' order by id  desc");
            if (rs.next()) {
                apidatas.put("status", false);
                apidatas.put("msg", "已授权");
                apidatas.put("errMsg", "派单失败,不在派单节点或者" + requestId + "已经在" + rs.getString("cjsj") + "派给了" + rs.getString("oper_workcode"));
                apidatas.put("code", "ERROR");
                Console.log(uuid + "返回值:" + apidatas.toString());
                rst.execute("update  uf_DispatchSSF set lctjzt='0' where request_id='" + requestId + "' and oper_workcode='" + dispatchWorkcode + "'");
                return apidatas;
            }
        }




        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "requestId="+requestId+"&remark="+Util.null2String(params.get("remark")));
        Request request = new Request.Builder()
                .url("http://127.0.0.1/api/workflow/paService/submitRequest")
                .method("POST", body)
                .addHeader("appid", Util.null2String(params.get("appid")))
                .addHeader("token", Util.null2String(params.get("token")))
                .addHeader("userid", Util.null2String(params.get("userid"))).addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = client.newCall(request).execute();

            String respStr = response.body().string();
            JSONObject result = JSONObject.parseObject(respStr);


            String code= Util.null2String(result.get("code"));

            if(!code.equals("SUCCESS")){
                apidatas.put("status",false);
                apidatas.put("msg","提交失败!");
                apidatas.put("errMsg",Util.null2String(result.get("errMsg")));
                apidatas.put("code",code);
                Console.log(uuid+"返回值:"+apidatas.toString());
                rs.execute("update  uf_DispatchSSF set lctjzt='1' where request_id='"+requestId+"' and oper_workcode='"+dispatchWorkcode+"' and cjsj='"+cjsj+"'");

                return apidatas;
            }else{
                rs.execute("update  uf_DispatchSSF set lctjzt='2' where request_id='"+requestId+"' and oper_workcode='"+dispatchWorkcode+"' and cjsj='"+cjsj+"'");
            }

        } catch (IOException e) {
            e.printStackTrace();
            e.printStackTrace();
            apidatas.put("status",false);
            apidatas.put("errMsg",e.toString());
            return apidatas;
        }

        Console.log(uuid+"返回值:"+apidatas.toString());
        return apidatas;
    }
}
